<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/29
 * Time: 14:32
 */
namespace App\Service\Live;

use App\Constant\RedisKeyConstant;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\MongoDB\LiveList;

class StatisticsService extends BaseService
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * every time count
     * @param int $live_id
     * @param int $time_interval
     * @return array
     */
    public function timeVisit(int $live_id, $time_interval = 6000)
    {
        /**
         * check live info
         */
        $live_info  =   LiveList::where(['Id' => $live_id])->select('StartTime', 'EndTime', 'HostId', 'Title')->first();
        if (empty($live_info)) {
            return [];
        }

        $start_time =   $live_info->StartTime;
        $end_time   =   $live_info->EndTime;
        $now_time   =   Carbon::now()->timestamp;
        $end_time   =   $now_time > $end_time ? $end_time : $now_time;

        $time_range =   range($start_time, $end_time, $time_interval);
        $time_array =   array_combine($time_range, array_fill(0, count($time_range), 0));

        return $this->timeCount($time_array, $live_info->name);
    }

    /**
     * get current time user watch count
     * @param $time_array
     * @param $room_name
     * @return array
     */
    public function timeCount($time_array = [], $room_name = '')
    {
        /**
         * get all watch users
         */
        $all_users  =   Redis::SMEMBERS(RedisKeyConstant::ROOM_WATCH_PEOPLE_NUMBER_PREFIX . $room_name);
        $new_time_array =   [];
        if (empty($all_users)) {
            return $new_time_array;
        }

        $time_keys  =   array_keys($time_array);
        foreach ($all_users as $user_id) {
            $user_line  =   Redis::LRANGE(RedisKeyConstant::USER_WATCH_LINE_PREFIX . $room_name . '_' . $user_id, 0, -1);
            if (empty($user_line)) {
                continue;
            }

            $watch_line =   [];
            foreach ($user_line as $single) {
                $watch_time =   explode('-', $single);
                $watch_line[]   =   $watch_time;
            }
            $watch_line =   array_reverse($watch_line);

            foreach ($time_keys as $time) {
                if ($this->timeSearch($time, $watch_line)) {
                    $new_time_array[$time][]    =   $user_id . '_' . $time;
                }
            }
        }

        return $new_time_array;
    }

    /**
     * if watch time in watch line
     * @param $time
     * @param $watch_array
     * @return bool
     */
    public function timeSearch($time, $watch_array)
    {
        foreach ($watch_array as $watch) {
            if (current($watch) <= $time && end($watch) >= $time) {
                return true;
            }

            if (end($watch) > $time) {
                return false;
            }
        }
        return false;
    }

}
